/**
 * Created by shenc on 2016/9/19.
 */

function MakeOrder(config) {
    var def = {
        biao: '',
        weixin: '',
        pingan: '',
        addUrl: '',
        editUrl: '',
        delUrl: '',
        ajaxInfo:''
    };

    var _self = this;
    this.config = $.extend(def, config || {});

    this.orderSection = $('#orderSection');
    this.cover = $('#addressCover');
    this.form = $('.J-formWrap').find('form');
    this.formType = 'add';
    this.formData = {};
    this.area = {};
    this.tpl = $('#addressTpl').html();
    this.addressList = $('.J-listWrap').find('.J-list');
    this.payLis = this.orderSection.find('.J-payType');
    this.payType = this.payLis.find('li').has('input[checked]').attr('data-type');
    this.couponList=$('.J-couponList');
    this.from=GetVar('from')||'';

    this._e = {
        //切换 支付方式
        changePayType: function () {
            var that = $(this);
            that.find('input').prop('checked', true);
            that.siblings('li').find('input').prop('checked', false);
            _self.payType = that.attr('data-type');
        },
        //去支付
        gotoPay: function (orderId) {
            var msg = _self.payType == 'alipay' ? '支付宝' : _self.payType == 'weixin' ? '微信' : _self.payType == 'pingan' ? '平安' : '支付宝';
            var payType=_self.payType == 'alipay' ? 1 : _self.payType == 'weixin' ? 3 : _self.payType == 'pingan' ? 4 : 1;

            if (msg == '') {
                topTip('请选择支付方式', {type: 'warn'});
                return false;
            }
            var dialog = $.dialog({
                title: '提示',
                content: '去' + msg + '支付',
                button: ['取消', '确认']
            });
            dialog.on("dialog:action", function (e) {
                if (e.index == 1) {
                    //去支付
                    Jump(_self.config[_self.payType]+'/'+orderId+'/'+payType);
                }else{
                    //去详情页
                    Jump(_self.config.orderDetail+'/'+orderId);
                }

            });
        },
        //确认订单
        checkOrder:function () {
            var form=_self.orderSection.find('form');
            var data=form.serialize();

            var lk=Locked();
            $.ajax({url:_self.config.makeOrder+'?from='+_self.from+'&_token='+_token,type:'post',dataType:'json',data:data,
                success:function(res){
                    if(typeof res.message != 'undefined' && res.message){
                        Alert(res.message);
                        return false;
                    }
                    _self._e.gotoPay(res[0]);
                },
                error:function(e){
                    topTip(e.responseText|e.message||'请求失败，请重试！',{type:'wran'});
                },
                complete:function(){
                    UnLocked(lk);
                }

            })
        },
        //弹框内跳转
        scrollTab: function (className) {
            _self.scroll.enable();
            _self.scroll.scrollToElement(className, 500, true, true);
            _self.scroll.disable();
        },
        //显示弹层
        showCover: function () {
            _self.cover.show();
            _self.scroll = new fz.Scroll('.ui-cover-wrap', {
                scrollY: false,
                scrollX: true
            });
            _self._e.scrollTab('.J-listWrap');
            setTimeout(function () {
                _self.cover.find('.J-mask').css('visibility', 'hidden');
            }, 500);
        },
        //隐藏弹层
        hideCover: function (cb) {
            $(window).scrollTop(0);
            setTimeout(function () {
                _self._e.scrollTab('.J-mask');
            }, 10);
            setTimeout(function () {
                _self.cover.hide();
                _self.cover.find('.J-mask').css('visibility', 'visible');
                _self.scroll.destroy();
            }, 500);
            typeof cb === 'function' && cb();
        },
        //删除收获地址
        removeAddress: function () {
            var li = $(this).closest('li'), id = li.attr('data-id'), isCur=li.find('input').prop('checked');
            var dg = $.dialog({
                title: '提示信息',
                content: '确定要删除吗？',
                button: ['取消', '确认']
            });

            dg.on('dialog:action', function (e) {
                if (e.index === 1) {
                    MyAjax(_self.config.delUrl + '/' + id+'?_token='+_token, 'delete', {}, function () {
                        var others=li.siblings('li');
                        if(others.length){
                            isCur&&others.eq(0).find('.ui-radio').triggerFastClick();
                        }else{
                            _self.formData={};
                            _self.renderOrder();
                        }
                        li.fadeOut(500, function () {
                            li.remove();
                        });
                    });
                }
            });
        },
        //编辑收获地址
        editAddress: function () {
            var that = $(this), li = that.closest('li');
            _self.getLiData(li);
            _self._e.scrollTab('.J-formWrap');
            _self.renderForm();
        },
        //收货地址-表单提交
        submitForm: function () {
            var isOk = RegForm(_self.form);
            if (!isOk) return isOk;
            _self.getFormData(_self.form.serializeArray());
            _self.formData['is_default'] || (_self.formData['is_default'] = 0);
            var url = _self.formType == 'add' ? _self.config.addUrl : (_self.config.editUrl + '/' + _self.addressId+'?_token='+_token);
            MyAjax(url, _self.formType == 'add' ? 'get' : 'put', _self.formData, function (res) {
                if(typeof res.message == 'string'&&res.message!=''){
                    Alert(res.message);
                    return false;
                }

                if (res.address_id) {
                    _self.formData.id = res.address_id;
                } else {
                    _self.formData.id = _self.addressId;
                    _self.addressId = null;
                }
                _self.form[0].reset();
                _self.renderLi(res);
                _self._e.hideCover();

            });
        },
        //表单地址变更
        areaChange: function () {
            var that = $(this), valArr = that.val().split(',');
            var province = that.siblings('[name="province"]');
            var city = that.siblings('[name="city"]');
            var district = that.siblings('[name="district"]');
            if (valArr.length == 0) {
                province.val('');
                city.val('');
                district.val('');
            } else {
                province.val(valArr[0]);
                city.val(valArr[1]);
                district.val(valArr[2]);
            }
        }
    };
    this.renderOrder = function () {
        var addressShow=_self.orderSection.find('.J-orderAddress');
        if(_self.formData.id){
            addressShow.find('.J-remove').hide()&&addressShow.find('.J-showT').show();
            addressShow.find('.J-name').text(_self.formData.consignee);
            addressShow.find('.J-phone').text(_self.formData.mobile);
            addressShow.find('.J-address').text(_self.formData.province + _self.formData.city + _self.formData.district + _self.formData.address);
            addressShow.find('#address_id').val(_self.formData.id);
        }else{
            addressShow.find('.J-remove').show()&&addressShow.find('.J-showT').hide();
            addressShow.find('.J-name').text('');
            addressShow.find('.J-phone').text('');
            addressShow.find('.J-address').text('');
            addressShow.find('#address_id').val('');
        }

    };
    this.renderOrderPrice=function (data) {
        _self.orderSection.find('.J-price').each(function () {
            var that=$(this);
            that.hasClass('order_price')&&that.text('¥'+(data.info['total_order_price']*1).toFixed(2));
            that.hasClass('tariff_fee')&&that.text('¥'+(data.info['total_tariff_fee']*1).toFixed(2));
            that.hasClass('shipping_fee')&&that.text('¥'+(data.info['total_shipping_fee']*1).toFixed(2));
            that.hasClass('coupon_price')&&that.text('¥'+(data.info['total_coupon_price']*1).toFixed(2));
            that.hasClass('pay_price')&&that.text('¥'+(data.info['total_pay_price']*1).toFixed(2));
        });
    };
    this.renderLi = function () {
        var newLi = $(HtmlTemplate(_self.tpl, _self.formData, true));
        var oldLi = _self.addressList.find('li[data-id="' + _self.formData.id + '"]');
        if (oldLi.length) {
            oldLi.replaceWith(newLi);
        } else {
            _self.addressList.prepend(newLi);
        }
        if (_self.formData.is_default == 1) {
            newLi.siblings('li').find('.J-item[data-name="is_default"]').attr('data-val', 0);
        }
        console.log('到此',newLi.find('.ui-radio'));
        newLi.find('.ui-radio').triggerFastClick();
    };
    this.renderForm = function () {
        var inputs = _self.form.find('input,textarea');
        for (var i = 0; i < inputs.length; i++) {
            var input = $(inputs[i]), name = input.attr('name');
            if (name == 'input_area') {
                continue;
            }
            if (name == 'is_default') {
                input.prop('checked', _self.formData['is_default'] * 1);
                continue;
            }
            input.val(_self.formData[name]);
        }
        //地址选择插件  赋值
        initAreaSelect({
            trigger: '#areaInput',
            valueTo: '#areaIds'
        });
    };
    this.getLiData = function (li) {
        var liData = {};
        var items = li.find('.J-item');
        for (var i = 0; i < items.length; i++) {
            var cur = $(items[i]);
            liData[cur.attr('data-name')] = cur.attr('data-val');
        }
        liData.id = li.attr('data-id');
        _self.formData = liData;
    };
    this.getFormData = function (serializeArr) {
        var liData = {};
        for (var i = 0; i < serializeArr.length; i++) {
            var cur = serializeArr[i];
            liData[cur.name] = cur.value;
        }
        _self.formData = liData;
    };
    this.ajaxInfo =function (callback) {
        var address_id=_self.orderSection.find('#address_id').val();
        var data={e_coupon_id:'',c_coupon_id:''};
        if(!address_id){
            Alert('请选择收货地址！');
            return false;
        }
        if(_self.couponList.length){
            var goodsType=_self.couponList.attr('data-type');
            var coupon=_self.couponList.find('input').filter(function(){return $(this).prop('checked');});
            var coupon_id=coupon.length?coupon.val():'';

            if(coupon.length){
                data[goodsType]=coupon_id;
            }
        }


        var lk=Locked();
        $.ajax({
            url:_self.config.ajaxInfo+'/'+address_id+'?from='+_self.from+'&_token='+_token,
            dataType:'json',
            type:'put',
            data:data,
            success:function(res){
                _self.renderOrderPrice(res);
                typeof callback=='function'&&callback(res);
            },
            error:function(e){
                topTip(e.responseText||e.message||'请求失败',{type:'warn'});
            },
            complete:function(){
                UnLocked(lk);
            }
        });

    };
    this.bind = function () {

        //切换 支付方式
        _self.orderSection.on('click', '.J-payType li', function () {
            _self._e.changePayType.call(this);
        });

        //确认订单（点击确认订单）
        _self.orderSection.on('click', '.J-submitBtn', function () {
            _self._e.checkOrder.call(this);
        });

        //触发弹出框（点击收货地）
        _self.orderSection.on('click', '.J-orderAddress', function () {
            _self._e.showCover();
        });

        //返回订单页面（点击顶部返回）
        _self.cover.on('click', '.J-listWrap .ui-icon-return', function () {
            _self._e.hideCover();
        });

        //切换地址
        _self.cover.on('click','.J-list input',function () {
            _self.getLiData($(this).closest('li'));
            _self.renderOrder();
            _self.ajaxInfo();
            _self._e.hideCover();
        });

        //添加地址
        _self.cover.on('click', '.J-add', function () {
            _self.formType = 'add';
            if(_self.addressList.find('li').length>=20){
                Alert('收货地址最多只能添加20个');
                return false;
            }
            _self._e.scrollTab('.J-formWrap');
        });

        //返回地址列表页面（点击form顶部返回）
        _self.cover.on('click', '.J-formWrap .ui-icon-return', function () {
            _self._e.scrollTab('.J-listWrap');
            _self.form[0].reset();
        });

        //编辑地址
        _self.cover.on('click', '.J-edit', function () {
            _self.formType = 'edit';
            _self.addressId = $(this).closest('li').attr('data-id');
            _self._e.editAddress.call(this);
        });

        //删除地址
        _self.cover.on('click', '.J-del', function () {
            _self._e.removeAddress.call(this);
        });

        //收货地址-表单提交
        _self.form.on('submit', function (e) {
            e.preventDefault();
            _self._e.submitForm.call(this);
            return false;
        });

        //确定添加
        _self.cover.on('click', '.J-submit', function () {
            _self.form.submit();
        });

        //表单地址变更
        _self.form.find('#areaInput').on('input', function () {
            _self._e.areaChange.call(this);
        });

        //选择优惠券
        _self.couponList.on('click','input',function () {
            var that=$(this);
            if(that.hasClass('cur')){
                _self.couponList.find('input').removeClass('cur');
                that.prop('checked',false);
            }else{
                that.addClass('cur');
                var lis=that.closest('li').siblings('li');
                lis.length&&lis.find('input').removeClass('cur');
            }
             _self.ajaxInfo();
        });

    };
    this.init = function () {
        //地址选择插件  赋值
        initAreaSelect({
            trigger: '#areaInput',
            valueTo: '#areaIds'
        });

        this.bind();
    };


    this.init();
}